package com.kk.flink;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
 * @author liukang
 * @since 2021/12/1 19:57
 */
public class WordCount {
    /**
     * 批处理 Word count api调用
     * 对数据集进行处理 是离线数据集 批处理
     */
    public static void main(String[] args) throws Exception {
        //创建执行环境 就是java上下文
        ExecutionEnvironment environment = ExecutionEnvironment.getExecutionEnvironment();

        //从文件中读取数据
        String inputPath = "C:\\Users\\kk_master001\\IdeaProjects\\BigData\\FlinkDemo\\src\\main\\resources\\hello.txt";
        DataSet<String> inputDataSet = environment.readTextFile(inputPath);

        //对数据集进行处理,按空格分词展开，转换为(word,1) 二元组进行统计
        DataSet<Tuple2<String, Integer>> resultSet = inputDataSet.flatMap(new MyflatMapper())
                //按照第一个位置的word分组
                .groupBy(0)
                //将第二个位置上的数据求和
                .sum(1);

        resultSet.print();
    }

    public static class MyflatMapper implements FlatMapFunction<String, Tuple2<String, Integer>> {

        @Override
        public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
            // 按空格分词
            String[] words = value.split(" ");
            for (String word : words) {
                out.collect(new Tuple2<>(word, 1));
            }
        }
    }
}
